package com.vast.admin.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vast.admin.annotation.PassToken;
import com.vast.admin.annotation.UseToken;
import com.vast.admin.entity.*;
import com.vast.admin.entity.dto.ContractDetailDto;
import com.vast.admin.entity.dto.ContractDto;
import com.vast.admin.entity.dto.SignerDTO;
import com.vast.admin.entity.enums.QueryOrderEnum;
import com.vast.admin.service.*;
import com.vast.admin.service.impl.CompanyService;
import com.vast.common.annotation.Log;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.common.utils.SecurityUtils;
import com.vast.common.utils.StringUtils;
import com.vast.common.constant.MessageCode;
import com.vast.common.core.domain.Result;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 合同 前端控制器
 * </p>
 *
 * @author zhaohao
 * @since 2019-11-09
 */
@RestController
@Api(value = "合同相关接口", tags = { "合同理模块" })
@RequestMapping("/manager/contract")
public class ContractController {


	@Autowired
	private ContractService service;

	@Autowired
	private ContractDetailService contractDetailService;

	@Autowired
	private TempleteService templeteService;

	@Autowired
	private PlaceholderService placeholderService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private CompanyService companyService;



	@ApiOperation(value = "查询列表信息", notes = "通过条件查询列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "size", value = "分页条数", dataType = "int", defaultValue = "10", required = false),
			@ApiImplicitParam(paramType = "query", name = "current", value = "页码,起始值:1", dataType = "int", defaultValue = "1", required = false),
			@ApiImplicitParam(paramType = "query", name = "listMode", value = "是否集合模式:true不进行分页直接返回所有结果集", dataType = "boolean", defaultValue = "false", required = false),
			@ApiImplicitParam(paramType = "query", name = "queryItems", value = "查询条件,json集合", defaultValue = "account,EQ,13419519796;", dataType = "String", required = false),
			@ApiImplicitParam(paramType = "query", name = "orderField", value = "排序字段,多个','分隔", defaultValue = "create_time", dataType = "String",  required = false),
			@ApiImplicitParam(paramType = "query", name = "order", value = "排序类型: ASC/DESC", dataType = "QueryOrderEnum",  required = false)
			})
	@GetMapping("/page")
	public Result<IPage<Contract>> pageContract(@ApiParam(hidden = true) Page<Contract> page, boolean listMode, String queryItems, String orderField, QueryOrderEnum order) {
		SysUser manager = SecurityUtils.getLoginUser().getUser();
		return new Result<>(MessageCode.SUCCESS, "获取成功", service.queryList(manager,page, listMode, queryItems, orderField,order));
	}

	@GetMapping("/list")
	public Result<IPage<Contract>> list(@ApiParam(hidden = true) Page<Contract> page, Contract contract) {
		IPage<Contract> list = service.queryContractList(page, contract);
		return new Result<IPage<Contract>>(MessageCode.SUCCESS, "获取成功", list);
	}


	@ApiOperation(value = "查询未完成合同列表", notes = "查询未完成合同列表(未上传资料和未签署完成合同)")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "size", value = "分页条数", dataType = "int", defaultValue = "10", required = false),
			@ApiImplicitParam(paramType = "query", name = "current", value = "页码,起始值:1", dataType = "int", defaultValue = "1", required = false),
			@ApiImplicitParam(paramType = "query", name = "listMode", value = "是否集合模式:true不进行分页直接返回所有结果集", dataType = "boolean", defaultValue = "false", required = false),
			@ApiImplicitParam(paramType = "query", name = "datumStatus", value = "是否完成资料上传", dataType = "int", defaultValue = "1", required = false),
			@ApiImplicitParam(paramType = "query", name = "status", value = "合同是否完成签署", dataType = "int", defaultValue = "0", required = false),
			@ApiImplicitParam(paramType = "query", name = "orderField", value = "排序字段,多个','分隔", defaultValue = "create_time", dataType = "String",  required = false),
			@ApiImplicitParam(paramType = "query", name = "order", value = "排序类型: ASC/DESC", dataType = "QueryOrderEnum",  required = false)
	})
	@GetMapping("/unCompleteContractPage")
	public Result<IPage<Contract>> unCompleteContractPage(@ApiParam(hidden = true) Page<Contract> page, boolean listMode, int datumStatus, int status, String orderField, String order) {
		SysUser manager = SecurityUtils.getLoginUser().getUser();
		return new Result<>(MessageCode.SUCCESS, "获取成功", service.unCompleteContractPage(manager,page, listMode, datumStatus, status, orderField,order));

	}


	@ApiOperation(value = "添加或更新合同", notes = "添加或更新合同")
	@UseToken
	@PostMapping("/addOrUpdate")
	@Log(title = "添加或更新合同")
	public Result<Contract> addOrUpdate(@RequestBody @ApiParam(name="Contract",value="Contract信息",required=true) Contract contract) {
		if(contract != null) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			boolean flag  = service.addOrUpdate(manager, contract);
			if(flag){
				return new Result<>(MessageCode.SUCCESS, "成功", contract);
			}else{
				return new Result<>(MessageCode.ERROR, "失败");
			}
		}else {
			return new Result<>(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "通过id获取信息", notes = "通过id获取信息")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true)})
	@GetMapping("/info/{id}")
	@UseToken
	@Log(title = "通过id获取信息")
	public Result<Contract> info(@PathVariable("id") Long id) {
		if(id != null && id.longValue() > 0){
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			Contract bean = service.info(manager,id);
			if(bean != null){
				return new Result<>(MessageCode.SUCCESS, "获取成功", bean);
			}else{
				return new Result<>(MessageCode.ERROR, "获取失败");
			}
		}
		return new Result<>(MessageCode.PARAM_ERROR, "id不能为空");
	}

	@ApiOperation(value = "删除", notes = "删除")
	@UseToken
	@Log(title = "删除合同")
	@DeleteMapping("/delete/{ids}")
	public Result<Boolean> delete(@PathVariable("ids") @ApiParam(name="ids",value="数据id数组,以','分隔",required=true) Long[] ids) {
		if(ids != null) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			boolean flag  = service.delete(manager, ids);
			if(flag){
				return new Result<>(MessageCode.SUCCESS, "删除成功");
			}else{
				return new Result<>(MessageCode.ERROR, "删除失败");
			}
		}else {
			return new Result<>(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "删除合同详情", notes = "删除合同详情")
	@UseToken
	@Log(title = "删除合同详情")
	@DeleteMapping("/deleteDetail")
	public Result<Boolean> deleteDetail(@RequestBody @ApiParam(name="ids",value="数据id数组,以','分隔",required=true) Long[] ids) {
		if(ids != null) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			boolean flag  = service.deleteDetail(manager, ids);
			if(flag){
				return new Result<>(MessageCode.SUCCESS, "删除成功");
			}else{
				return new Result<>(MessageCode.ERROR, "删除失败");
			}
		}else {
			return new Result<>(MessageCode.PARAM_ERROR, "参数错误");
		}
	}


	@ApiOperation(value = "获取合同签署流程里的合同列表", notes = "获取合同签署流程里的合同列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同流程ID", dataType = "Long", required = false)
	})
	@UseToken
	@Log(title = "获取合同签署流程里的合同列表")
	@GetMapping("/getFlowContractList")
	public Result getFlowContractList(Long contractId){
		if(contractId != null && contractId > 0) {
			List<ContractDetail> result = contractDetailService.getByContractId(contractId);
			return new Result(MessageCode.SUCCESS, "获取成功", result);
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "获取合同预览链接", notes = "获取合同预览链接 注: 合同状态签署中的,即status>=3")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同ID", dataType = "Long", required = false)
	})
	@UseToken
	@Log(title = " 获取合同预览链接")
	@GetMapping("/getContractPreviewUrl")
	public Result getContractPreviewUrl( Long contractId){
		if(contractId != null && contractId > 0) {
			String result = service.getContractPreviewUrl(contractId);
			return new Result(MessageCode.SUCCESS, "获取成功", result);
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "下载已签署合同", notes = "下载已签署合同")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "id", value = "合同ID", dataType = "Long", required = true)
	})
	@PassToken
	@GetMapping("/downloadContract")
	public void downloadContract(HttpServletResponse response, Long id) {
		service.downloadContract(response, id);
	}

	@ApiOperation(value = "重新推送合同签署链接", notes = "重新推送合同签署链接")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同ID", dataType = "Long", required = true),
			@ApiImplicitParam(paramType = "query", name = "customerId", value = "客户ID", dataType = "Long", required = true)
	})
	@UseToken
	@Log(title = " 重新推送合同签署链接")
	@GetMapping("/repushContractUrl")
	public Result<Void> repushContractUrl(Long contractId, Long customerId) {
		service.repushContractUrl(contractId, customerId);
		return Result.SUCCESS;
	}

	@ApiOperation(value = "获取合同签署者信息", notes = "获取合同签署者信息")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同ID", dataType = "Long", required = true)
	})
	@UseToken
	@Log(title = " 获取合同签署者信息")
	@GetMapping("/getSigners")
	public Result<List<SignerDTO>> getSigners(Long contractId) {
		return new Result<>(MessageCode.SUCCESS, service.getSignerDTOList(contractId));
	}

	@ApiOperation(value = "作废合同", notes = "作废合同")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同ID", dataType = "Long", required = true)
	})
	@UseToken
	@Log(title = " 作废合同")
	@GetMapping("/cancelContract")
	public Result<Void> cancelContract(Long contractId) {
		SysUser manager = SecurityUtils.getLoginUser().getUser();
		service.cancelContract(contractId, manager);
		return Result.SUCCESS;
	}


	@ApiOperation(value = "查询合同模版列表", notes = "查询合同模版列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "size", value = "分页条数", dataType = "int", defaultValue = "10", required = false),
			@ApiImplicitParam(paramType = "query", name = "current", value = "页码,起始值:1", dataType = "int", defaultValue = "1", required = false),
			@ApiImplicitParam(paramType = "query", name = "listMode", value = "是否集合模式:true不进行分页直接返回所有结果集", dataType = "boolean", defaultValue = "false", required = false),
			@ApiImplicitParam(paramType = "query", name = "queryItems", value = "查询条件,json集合", defaultValue = "account,EQ,13419519796;", dataType = "String", required = false),
			@ApiImplicitParam(paramType = "query", name = "orderField", value = "排序字段,多个','分隔", defaultValue = "create_time", dataType = "String",  required = false),
			@ApiImplicitParam(paramType = "query", name = "order", value = "排序类型: ASC/DESC", dataType = "QueryOrderEnum",  required = false)
	})
	@UseToken
	@GetMapping("/getTemplateList")
	public Result<IPage<Templete>> page(@ApiParam(hidden = true) Page<Templete> page, boolean listMode, String queryItems, String orderField, QueryOrderEnum order) {
		SysUser manager = SecurityUtils.getLoginUser().getUser();
		return new Result<IPage<Templete>>(MessageCode.SUCCESS, "获取成功", templeteService.queryAppContractTemplateList(manager,page, listMode, queryItems, orderField,order));
	}


	@ApiOperation(value = "根据模版记录id获取模版属性配置字段", notes = "根据模版记录id获取模版属性配置字段")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "id", value = "合同记录模版id", dataType = "Long",  required = true)
	})
	@UseToken
	@GetMapping("/getTemplateFieldsById")
	public Result getTemplateFieldsByTemplateRecordId(Long id) {
		if(id != null) {
			List<Map<String, Object>> templateFields  = placeholderService.getPlaceholderByTempleteRecordId(id);
			if(templateFields != null){
				return new Result(MessageCode.SUCCESS, "获取成功", templateFields);
			}else{
				return new Result(MessageCode.ERROR, "获取失败");
			}
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "根据客户手机号码查询客户", notes = "根据客户手机号码查询客户")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "type", value = "类型:企业方:1:企业方,3:担保方,4:其它企业 ; 2: 客户方", dataType = "int", required = true),
			@ApiImplicitParam(paramType = "query", name = "phone", value = "手机号码", dataType = "String",  required = true)
	})
	@UseToken
	@Log(title = "根据客户手机号码查询客户")
	@GetMapping("/getCustomerByPhone")
	public Result getCustomerByPhone(String phone, Integer type) {
		if(!StringUtils.isEmpty(phone) && type != null) {
			if(type == 2){
				Customer customer = customerService.getCustomerByPhone(phone);
				if(customer != null){
					return new Result(MessageCode.SUCCESS, "获取成功", customer);
				}else{
					return new Result(MessageCode.SUCCESS, "查无此数据");
				}
			}else if(type == 1 || type == 3 || type ==4){
				Company company =companyService.getCompanyByPhone(phone);
				if(company != null){
					return new Result(MessageCode.SUCCESS, "获取成功", company);
				}else{
					return new Result(MessageCode.SUCCESS, "查无此数据");
				}
			}
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "创建合同签署流程", notes = "创建合同签署流程")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "contractDao", value = "合同流程信息", dataType = "ContractDto",  required = true)
	})
	@UseToken
	@Log(title = "创建合同签署流程")
	@PostMapping("/createContract")
	public Result createContract(ContractDto contractDao) {
		if(contractDao != null) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			Long contractId = service.createContract(contractDao,manager);
			if(contractId != null){
				return new Result(MessageCode.SUCCESS, "创建成功", contractId);
			}else{
				return new Result(MessageCode.ERROR, "创建失败");
			}
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "添加合同签署流程客户", notes = "添加合同签署流程客户")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "contractDao", value = "合同流程信息", dataType = "ContractDto",  required = true)
	})
	@UseToken
	@Log(title = "添加合同签署流程客户")
	@PostMapping("/addContractCustomer")
	public Result addContractCustomer(ContractDto contractDao) {
		if(contractDao != null && contractDao.getCustomerId() != null) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			Long contractId = service.addContractCustomer(contractDao,manager);
			if(contractId != null){
				return new Result(MessageCode.SUCCESS, "添加成功", contractId);
			}else{
				return new Result(MessageCode.ERROR, "添加失败");
			}
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}


	@ApiOperation(value = "保存合同信息", notes = "保存合同信息")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "header", name = "token", value = "登录获取的token", dataType = "String", required = true),
			@ApiImplicitParam(paramType = "query", name = "contractDetailDto", value = "合同信息", dataType = "ContractDetailDto",  required = true)
	})
	@UseToken
	@Log(title = "保存合同信息")
	@PostMapping("/saveContractDetail")
	public Result saveContractDetail(@RequestBody ContractDetailDto contractDetailDto) {
		if(contractDetailDto != null) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			boolean flag = service.saveContractDetail(contractDetailDto,manager);
			if(flag){
				return new Result(MessageCode.SUCCESS, "保存成功");
			}else{
				return new Result(MessageCode.ERROR, "保存失败");
			}
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}

	@ApiOperation(value = "获取合同签署流程列表", notes = "获取合同签署流程列表")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "size", value = "分页条数", dataType = "int", defaultValue = "10", required = false),
			@ApiImplicitParam(paramType = "query", name = "current", value = "页码,起始值:1", dataType = "int", defaultValue = "1", required = false),
			@ApiImplicitParam(paramType = "query", name = "listMode", value = "是否集合模式:true不进行分页直接返回所有结果集", dataType = "boolean", defaultValue = "false", required = false),
			@ApiImplicitParam(paramType = "query", name = "queryItems", value = "查询条件,json集合", defaultValue = "account,EQ,13419519796;", dataType = "String", required = false),
			@ApiImplicitParam(paramType = "query", name = "orderField", value = "排序字段,多个','分隔", defaultValue = "create_time", dataType = "String",  required = false),
			@ApiImplicitParam(paramType = "query", name = "order", value = "排序类型: ASC/DESC", dataType = "QueryOrderEnum",  required = false)
	})
	@UseToken
	@GetMapping("/getContractList")
	public Result<IPage<Contract>> getContractList(@ApiParam(hidden = true) Page<Contract> page, boolean listMode, String queryItems, String orderField, QueryOrderEnum order) {
		SysUser manager = SecurityUtils.getLoginUser().getUser();
		return new Result<IPage<Contract>>(MessageCode.SUCCESS, "获取成功", service.queryList(manager,page, listMode, queryItems, orderField,order));
	}


	@ApiOperation(value = "锁定并生成合同", notes = "锁定并生成合同")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "id", value = "合同流程ID", dataType = "Long", required = false),
			@ApiImplicitParam(paramType = "query", name = "flag", value = "是否检查签署者（0检查 1忽略）", dataType = "Integer", required = false)
	})
	@UseToken
	@Log(title = "锁定并生成合同")
	@GetMapping("/lockAndProduceContract")
	public Result lockAndProduceContract(Long id, @RequestParam(defaultValue = "0") Integer flag){
		if(id != null && id > 0) {
			SysUser manager = SecurityUtils.getLoginUser().getUser();
			service.productionContract(id, manager, flag);
			return new Result(MessageCode.SUCCESS, "操作成功");
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}



	@ApiOperation(value = "获取合同签署流程里的合同详情", notes = "获取合同签署流程里的合同详情")
	@ApiImplicitParams({
			@ApiImplicitParam(paramType = "query", name = "contractId", value = "合同ID", dataType = "Long", required = false)
	})
	@UseToken
	@GetMapping("/getContractDetailById")
	public Result getContractDetailById(Long contractId){
		if(contractId != null && contractId > 0) {
			ContractDetailDto result = service.getContractDetail(contractId);
			return new Result(MessageCode.SUCCESS, "获取成功", result);
		}else {
			return new Result(MessageCode.PARAM_ERROR, "参数错误");
		}
	}




}
